import pymysql


class DataSaver(object):

    def __init__(self):
        self.db = pymysql.connect('localhost', 'root', 'wangjq', 'webcrawer', charset = "utf8")
        self.cursor = self.db.cursor()

    def save_data(self, datas):

        insert_sql = """INSERT INTO 
        `webcrawer`.`css`
        (URL,TITLE,CONTENT,reference_list) 
        VALUES ("{}","{}","{}","{}");""" .format(datas ['url'], datas ['title'], datas ['summary'], datas ['reference_list'])

        try:
            # 执行sql语句
            self.cursor.execute(insert_sql)
            self.db.commit()
            print('写入数据库成功')
        except BaseException as e:
            # 发生错误时回滚
            print('写入数据库失败',e)
            self.db.rollback()
